package com.cb2.algorithm.leetcode;

import java.util.LinkedList;
import java.util.Queue;

/**
 * <a href="https://leetcode.cn/problems/invert-binary-tree/">反转二叉树(Invert Binary Tree)</a>
 * <p>给你一棵二叉树的根节点 root ，翻转这棵二叉树，并返回其根节点。</p>
 * <p>
 * <b>示例：</b>
 * <pre>
 * 示例 1：
 *      输入：root = [4,2,7,1,3,6,9]
 *               4
 *             /   \
 *            2     7
 *           / \   / \
 *          1   3 6   9
 *      输出：[4,7,2,9,6,3,1]
 *
 * 示例 2：
 *      输入：root = [2,1,3]
 *                2
 *               / \
 *              1   3
 *      输出：[2,3,1]
 *
 * 示例 3：
 *      输入：root = []
 *      输出：[]
 * </pre>
 * </p>
 * <p>
 * <b>提示：</b>
 * <ul>
 *     <li>树中节点数目范围在 [0, 100] 内</li>
 *     <li>-100 <= Node.val <= 100</li>
 * </ul>
 * </p>
 *
 * @author c2b
 * @since 2023/5/15 16:04
 */
public class LC0226InvertBinaryTree_S {

    static class Solution {
        public TreeNode invertTree(TreeNode root) {
            return invertTreeByIteration(root);
            //return invertTreeByRecursion(root);
        }

        private TreeNode invertTreeByIteration(TreeNode root) {
            if (root == null) {
                return null;
            }
            Queue<TreeNode> queue = new LinkedList<>();
            queue.offer(root);
            while (!queue.isEmpty()) {
                TreeNode currNode = queue.poll();
                TreeNode left = currNode.left;
                currNode.left = currNode.right;
                currNode.right = left;
                if (currNode.left != null) {
                    queue.offer(currNode.left);
                }
                if (currNode.right != null) {
                    queue.offer(currNode.right);
                }
            }
            return root;
        }

        private TreeNode invertTreeByRecursion(TreeNode root) {
            if (root == null) {
                return null;
            }
            // 递归交换当前节点的 左子树
            TreeNode left = invertTreeByRecursion(root.left);
            // 递归交换当前节点的 右子树
            TreeNode right = invertTreeByRecursion(root.right);
            root.left = right;
            root.right = left;
            return root;
        }
    }
}